#include "sqlite_helper.h"

SqliteHelper::~SqliteHelper() {
    // 同Close()
    if (database_.isOpen()) {
        qDebug() << "Close database";
        database_.close();
    }
    qDebug() << "~SqliteHelper()";
}


bool SqliteHelper::Initialize(const QString &database_name, const QString &connect_name) {
    if(QSqlDatabase::contains(connect_name)) {
        database_ = QSqlDatabase::database(connect_name);
    } else {
        database_ = QSqlDatabase::addDatabase("QSQLITE", connect_name);
        database_.setDatabaseName(database_name + ".db");
    }

    bool database_is_open = database_.open();
    if (database_is_open) {
        qDebug() << "";
    } else {
        qDebug() << database_.lastError();
    }
    return database_is_open;
}

bool SqliteHelper::ExecuteCommand(std::unique_ptr<SqliteCommandInterface> &&cmd)
{
    std::unique_ptr<SqliteCommandInterface> write_cmd = std::move(cmd);
    return write_cmd->Execute(database_);
}

bool SqliteHelper::ExecuteCommand(std::shared_ptr<SqliteCommandInterface> &&cmd)
{
    return cmd->Execute(database_);
}

std::optional<QSqlQuery> SqliteHelper::ExecuteQuery(std::unique_ptr<SqliteQueryInterface> &&query)
{
    return query->Execute(database_);
}

std::optional<QSqlQuery> SqliteHelper::ExecuteQuery(std::shared_ptr<SqliteQueryInterface> &&query)
{
    return query->Execute(database_);
}

void SqliteHelper::Close() {
    if (database_.isOpen()) {
        qDebug() << "Close database";
        database_.close();
    }
}

QSqlDatabase SqliteHelper::GetDataBase()
{
    return database_;
}



